using System.Linq;
using Jurassic;
using Jurassic.Library;

namespace Kiwi.Node.Modules.Builtin
{
    public class Amd: BuiltinModuleObject
    {
        public Amd(IApplication application) : base(application)
        {
        }

        [JSFunction(Name = "resolveModule")]
        public object ResolveModule(string folder, string module)
        {
            var resolvedModule = (from mr in Application.ModuleResolvers
                                  let rm = mr.TryResolveDynamic(Application,folder, module)
                                  where rm != null
                                  select rm
                                  )
                .FirstOrDefault();

            if (resolvedModule == null)
            {
                return Undefined.Value;
            }

            return new AmdResolve(Application, resolvedModule);
        }

        public class AmdResolve: BuiltinModuleObject
        {
            public IResolvedModule ResolvedModule { get; private set; }

            public AmdResolve(IApplication application, IResolvedModule resolvedModule): base(application)
            {
                ResolvedModule = resolvedModule;
                this["key"] = resolvedModule.Key;
                this["path"] = resolvedModule.Path;
            }

            [JSFunction(Name = "resolve")]
            public object Resolve()
            {
                return ResolvedModule.Resolve(Application);
            }
        }
    }
}